package com.zhang.req.cep;

import com.zhang.second.utils.OrderEvents;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * @title: 订单超时检测  CEP实现
 * @author: zhang
 * @date: 2022/2/3 08:16
 */
public class OrderTimeOut {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        KeyedStream<OrderEvents, String> orderEventsDS = env
                .readTextFile("/Users/apple/IdeaProjects/flink_1.13/src/main/resources/OrderLog.csv")
                .map(new MapFunction<String, OrderEvents>() {
                    @Override
                    public OrderEvents map(String value) throws Exception {
                        String[] fields = value.split(",");
                        return new OrderEvents(
                                fields[0], fields[1], fields[2],
                                Long.parseLong(fields[3]) * 1000L
                        );
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<OrderEvents>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<OrderEvents>() {
                                    @Override
                                    public long extractTimestamp(OrderEvents element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })

                )
                .keyBy(r -> r.orderId);

        Pattern<OrderEvents, OrderEvents> pattern = Pattern.<OrderEvents>begin("order")
                .where(new SimpleCondition<OrderEvents>() {
                    @Override
                    public boolean filter(OrderEvents value) throws Exception {
                        return "create".equals(value.type);
                    }
                })
                .followedBy("pay")
                .where(new SimpleCondition<OrderEvents>() {
                    @Override
                    public boolean filter(OrderEvents value) throws Exception {
                        return "pay".equals(value.type);
                    }
                })
                .within(Time.minutes(15));

        PatternStream<OrderEvents> patternStream = CEP.pattern(orderEventsDS, pattern);

        SingleOutputStreamOperator<String> result = patternStream.select(new OutputTag<String>("no pay") {
                                                                         },
                new PatternTimeoutFunction<OrderEvents, String>() {
                    @Override
                    public String timeout(Map<String, List<OrderEvents>> pattern, long timeoutTimestamp) throws Exception {
                        OrderEvents createEvent = pattern.get("order").get(0);
                        return "订单：" + createEvent.orderId + "只有创建没有支付";
                    }
                },
                new PatternSelectFunction<OrderEvents, String>() {
                    @Override
                    public String select(Map<String, List<OrderEvents>> pattern) throws Exception {
                        OrderEvents createEvent = pattern.get("order").get(0);
                        OrderEvents payEvent = pattern.get("pay").get(0);
                        return createEvent.orderId + "在" + createEvent.ts + "" +
                                "创建订单，并在" + payEvent.ts + "支付";
                    }
                }
        );

        result.print();

        result.getSideOutput(new OutputTag<String>("no pay") {
        }).print("no pay");


        env.execute();
    }
}
